package utils

import (
	"errors"
	"github.com/golang-jwt/jwt/v5"
	"time"
)

type JWTManager struct {
	secret    string
	algorithm string
}

func NewJWTManager(secret string) *JWTManager {
	return &JWTManager{
		secret:    secret,
		algorithm: "HS256",
	}
}

// 生成访问令牌，120分钟有效
func (j *JWTManager) CreateAccessToken(uuid string) (string, error) {
	claims := jwt.MapClaims{
		"uuid": uuid,
		"exp":  time.Now().Add(120 * time.Minute).Unix(),
		"iat":  time.Now().Unix(),
	}
	token := jwt.NewWithClaims(jwt.GetSigningMethod(j.algorithm), claims)
	return token.SignedString([]byte(j.secret))
}

// 生成刷新令牌，30天有效
func (j *JWTManager) CreateRefreshToken(uuid string) (string, error) {
	claims := jwt.MapClaims{
		"uuid": uuid,
		"exp":  time.Now().Add(30 * 24 * time.Hour).Unix(),
		"iat":  time.Now().Unix(),
	}
	token := jwt.NewWithClaims(jwt.GetSigningMethod(j.algorithm), claims)
	return token.SignedString([]byte(j.secret))
}

// 验证Token并返回payload
func (j *JWTManager) VerifyToken(tokenStr string) (jwt.MapClaims, error) {
	token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
		if token.Method.Alg() != j.algorithm {
			return nil, errors.New("unexpected signing method")
		}
		return []byte(j.secret), nil
	})
	if err != nil {
		return nil, err
	}

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims, nil
	}
	return nil, errors.New("invalid token")
}
